package com.flats.webview;


import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.io.IOException;
import java.math.BigInteger;
import java.util.*;

public class Utils {
    static {
        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapter(BigInteger.class, new TypeAdapter<BigInteger>() {
            @Override
            public BigInteger read(JsonReader in) throws IOException {
                if (in.peek() == JsonToken.NULL) {
                    in.nextNull();
                    return null;
                }
                try {
                    return new BigInteger(in.nextString());
                } catch (NumberFormatException e) {
                    throw new JsonSyntaxException(e);
                }
            }

            @Override
            public void write(JsonWriter out, BigInteger value) throws IOException {
                out.value(String.valueOf(value));
            }
        });
        GSON = gson.create();
    }

    public static final Gson GSON;

    public static void setSession(String key, Object value) {
        RequestAttributes attr = RequestContextHolder.currentRequestAttributes();
        attr.setAttribute(key, value, RequestAttributes.SCOPE_GLOBAL_SESSION);
    }

    public static Object getSession(String key) {
        RequestAttributes attr = RequestContextHolder.currentRequestAttributes();
        return attr.getAttribute(key, RequestAttributes.SCOPE_GLOBAL_SESSION);
    }

}
